package com.service.garbage.ningbo;

import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.service.bean.device.Vehicle;
import com.service.bean.garbage.GarbageCommnt;
import com.service.cache.CacheManager;
import com.service.other.Logger;

/**
 * 垃圾称重数据 调用远程接口 发送指定数据
 * @author zyf
 *
 */
public class GarbageAddress {
	/**
	 * 车辆
	 */
	private Vehicle vehicle;
	/**
	 * 接口服务名
	 */
	private String service;
	/**
	 * 接口方法名
	 */
	private String methodName;
	/**
	 * 接口参数
	 */
	private String sendMessage;
	/**
	 * 是否是第三个接口
	 */
	private boolean isThirdImpl = false;
	
	/**
	 * 多参
	 * @param vehicle 车辆
	 * @param service 接口服务名
	 * @param methodName 接口方法名
	 * @param sendMessage 接口参数
	 */
	public GarbageAddress(Vehicle vehicle ,String service,String methodName,String sendMessage)  {
		this.vehicle = vehicle;
		this.service = service;
		this.methodName = methodName;
		this.sendMessage = sendMessage;
	}
	
	/**
	 * 拼接地址, 发送数据包, 称重接口
	 */
	public void sendWeight() {
		try {
			isThirdImpl = false;
			StringBuilder builder = new StringBuilder();
			builder.append("http://garservice.nbzhhw.com/webservice/");
			builder.append(service);
			builder.append(".asmx/");
			builder.append(methodName);
			builder.append("?jsonMaram=");
			URI localURI = new URI(builder.toString() + URLEncoder.encode(sendMessage.toString(), "UTF-8"));
			String url = localURI.toASCIIString();
			doGetStr(vehicle, url);
		} catch (Exception e) {
			Logger.err(e);
		}
	}
	
	/**
	 * 拼接地址, 发送数据包, 车辆监控接口
	 */
	public void sendTrackData() {
		try {
			isThirdImpl = false;
			StringBuilder builder = new StringBuilder();
			builder.append("http://garservice.nbzhhw.com/webservice/CarTrackDataService.asmx/SendTrackData?jsonMaram=");
			System.out.println("url: " + builder.toString() + sendMessage);
			URI localURI = new URI(builder.toString() + URLEncoder.encode("{" + sendMessage.toString() + "}", "UTF-8"));
			String url = localURI.toASCIIString();
			doGetStr(vehicle, url);
		} catch (Exception e) {
			Logger.err(e);
		}
	}
	
	/**
	 * 拼接地址, 发送数据包, 查询小区接口
	 */
	public void getCommntInfo() {
		try {
			isThirdImpl = true;
			StringBuilder builder = new StringBuilder();
			builder.append("http://garservice.nbzhhw.com/webservice/CommntInfoService.asmx/GetCommntInfo?jsonMaram=");
			System.out.println("url: " + builder.toString() + sendMessage);
			URI localURI = new URI(builder.toString() + URLEncoder.encode("{" + sendMessage.toString() + "}", "UTF-8"));
			String url = localURI.toASCIIString();
			doGetStr(vehicle, url);
		} catch (Exception e) {
			Logger.err(e);
		}
	}
	
	/**
	 * 发送数据包, 接收返回信息
	 * @param vehicle 车辆
	 * @param url 接口地址
	 */
	public void doGetStr(Vehicle vehicle, String url) {
		try {
			DefaultHttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);
			client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
			HttpResponse response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String result = EntityUtils.toString(entity, "GBK");
				Logger.debug(vehicle.device.deviceNo, "返回值为:" + result);
				result = result.replaceAll("&lt;", "<");
				result = result.replaceAll("&gt;", ">");
				if (!isThirdImpl) {
					// 不是第三个接口, 只从返回的结果值中获取响应值
					xmlElements(vehicle, result);
				} else {
					result = result.replaceAll("\r\n", "");
					result = result.replaceAll(" ", "");
					// 是第三个接口, 解析json
					parseJson(result);
				}
			} else {
				Logger.debug(vehicle.device.deviceNo, "【新世纪】无返回数据, Json=" + sendMessage);
			}
		} catch (Exception e) {
			Logger.debug(vehicle.device.deviceNo, "【新世纪】请求或响应失败, Json=" + sendMessage);
			Logger.err(e);
		}
	}
	
	/**
	 * 解析返回信息, 并记录日志
	 * @param vehicle 车辆
	 * @param xmlDoc 接口返回信息
	 */
	private void xmlElements(Vehicle vehicle, String xmlDoc) {
		try {
			Document document = DocumentHelper.parseText(xmlDoc);
			// 拿到根节点
			Element root = document.getRootElement();
			String result = root.elementTextTrim("Result");
			String gpsno = vehicle.device.deviceNo;
			if ("1".equals(result)) {
				Logger.debug(gpsno, "返回值：" + result + " ,数据传输成功! Json=" + sendMessage);
			} else if ("0".equals(result)) {
				Logger.debug(gpsno, "返回值：" + result + " ,数据传输失败, Json=" + sendMessage);
			} else if ("9".equals(result)) {
				Logger.debug(gpsno, "返回值：" + result + " ,密钥不正确, Json=" + sendMessage);
			} else {
				Logger.debug(gpsno, "无返回值, Json=" + sendMessage);
			}
		} catch (Exception e) {
			Logger.err(e);
		}

	}
	
	/**
	 * 解析Json字符串, 将其解析成小区对象, 刷新对应缓存
	 * @param json
	 */
	private void parseJson(String json) {
		final String protocol = "\"ID\":(?<id>\\d+),\"CommntNo\":\"(?<commntNo>\\w+)\",\"CommntName\":\"(?<commntName>\\w*|\\W*|[\\u4e00-\\u9fa5]*)\",\"Longitude\":(?<longitude>\\d+\\.\\d+),\"latitude\":(?<latitude>\\d+\\.\\d+)";
		try {
			Pattern p = Pattern.compile(protocol);
			Matcher m = p.matcher(json);
			GarbageCommnt gc = null;
			List<GarbageCommnt> list = new ArrayList<GarbageCommnt>();
			System.out.println(m.find());
			while (m.find()) {
				gc = new GarbageCommnt();
				gc.id = m.group("id");
				gc.commntNo = m.group("commntNo");
				gc.commntName = m.group("commntName");
				gc.setLngAndLat(m.group("longitude"), m.group("latitude"));
				list.add(gc);
			}
			if (0 != list.size()) {
				CacheManager.instance().garbageCommnts = list;
				Logger.debug("cache", "成功刷新小区信息: " + json);
			} else {
				Logger.debug("cache", "刷新小区信息失败: " + json);
			}
		} catch (Exception e) {
			Logger.err(e);
			Logger.debug("cache", "刷新小区信息错误!: " + json);
		}
	}
	
}
